<template>
    <div>
        <van-nav-bar title="购物车" />
        <div id="cartInfo" v-if="userId">
        <!-- <van-pull-refresh v-model="isRefresh" @refresh="onRefresh"> -->
            <div v-if="cartInfo.length>0">
                <van-list
                v-model="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad"
                >
                    <div class="cart-list">
                        <van-checkbox-group v-model="result" ref="checkboxGroup">
                            <van-checkbox v-model="checkedGoods" :name="item.goodsId" v-for="(item,index) in cartInfo" :key="index" @click="checkGoods" label-disabled>
                                <div class="goods">
                                    <div class="goods-img">
                                        <img :src="item.img" width="100%"/>
                                    </div>
                                    <div class="goods-text">
                                        <div class="goods-name">{{item.name}}</div>
                                        <div class="goods-text-bottom">
                                            <div class="goods-price">￥{{item.price}}</div>
                                            <div class="goods-count">
                                                <van-stepper v-model="item.quanity" @change="changeQuanity(item.id,item.quanity)"  />
                                            </div>
                                            
                                        </div>
                                        <div class="cart-deleteBtn" @click="deleteCartGoods(item.id)">删除</div>
                                    </div>
                                    
                                </div>
                            </van-checkbox>
                        </van-checkbox-group>
                    </div>
                </van-list>
            </div>
            <div v-else >
                <div class="notic_text" style="margin-top:0">
                    <!-- <p class="notic_text_tit">当前购物车为空</p> -->
                    <div class="notic_text_div" >
                        <router-link :to="{path:'/classify'}" >
                            <span style="background-color: orange"><van-icon name="search" /></span>
                        </router-link>
                        <p style="margin-bottom:0;">购物车竟然为空</p>
                        <p style="font-size:13px;">再忙，也要记得买点东西犒劳自己~~</p>
                        <!-- <div style="display: flex; justify-content:center; font-size:13px;marign-top:0"><p>再忙，也要记得买点东西犒劳自己</p><p style="color:blue" @click="jumpLogin">登录</p></div> -->
                    </div>
                    
                </div>
            </div>
        </div>
        <div v-else>
            <div class="notic_text">
                <p class="notic_text_tit">未登陆账号</p>
                <div class="notic_text_div">
                    <span ><van-icon name="weapp-nav" /></span>
                    
                    <h5 style="display: flex; justify-content:center"><p>请先</p><p style="color:blue" @click="jumpLogin">登录</p></h5>
                </div>
                
            </div>
        </div>
        <!-- </van-pull-refresh> -->
        
        <div class="cart-bottom">
            <van-submit-bar :price="totalPrice" button-text="结算" @submit="onSubmit">
                <van-checkbox v-model="checked" @click="allCheck" ref="checkbox">全选</van-checkbox>
                <!-- <template #tip>
                    你的收货地址不支持同城送, <span @click="onClickEditAddress">修改地址</span>
                </template> -->
            </van-submit-bar>
        </div>
    </div>
</template>

<script>
    import axios from 'axios'
    import { Toast } from 'vant'
    export default {
        data(){
            return {
                userId: null,
                checkedGoods: false,
                result: [],
                isEmpty: false,
                cartInfo: [],
                checked: false,
                totalPrice: 0,
                pageNum: 1,  //商品列表页数
                loading: false,   //上拉加载使用
                finished: false,  //上拉加载是否没有数据了
                goodsStock: null,  //商品库存
            }
        },
        created(){
            if(localStorage.userInfo){
                let userInfo = JSON.parse(localStorage.userInfo)
                this.userId = userInfo.userId
                console.log("===========",this.userId);
                this.getcartInfo()
            }
            
        },
        mounted(){//mounted挂载完成
        if(this.userId){
            let winHeight = document.documentElement.clientHeight
            document.getElementById('cartInfo').style.height=winHeight-152 +'px'
        }
            
        },
        methods: {
            checkGoods(){
                console.log("======",this.result);
                this.totalPrice = 0
                for(let item of this.result){
                    for(let val of this.cartInfo){
                        if(item === val.goodsId){
                            this.totalPrice += val.price*val.quanity*100
                        }
                    }
                }
            },
            getcartInfo(){
                 axios({
                        url: 'http://localhost:3000/goods/cartGoodsInfo',
                        method: 'post',
                        data:{ 
                            userId: this.userId,
                            pageNum: this.pageNum
                        }   
                    }).then(res =>{
                        const { status,data} = res
                        if(status === 200){
                            if(data.message){
                                this.pageNum++
                                this.cartInfo=this.cartInfo.concat(data.message)
                                console.log(this.cartInfo);
                            }else{
                                this.finished = true;
                            }
                        }else{
                            Toast('服务器错误，数据取得失败')
                        }

                        this.loading=false;
                        console.log(this.finished)
                    })
            },
            
            allCheck(){
                // this.$refs.checkbox.toggle();
                this.result = []
                console.log("---------==============",this.checked);
                if(this.checked === true){
                    this.totalPrice = 0
                    for(let item of this.cartInfo){
                        this.result.push(item.goodsId)
                        this.totalPrice += item.price*item.quanity*100
                        console.log("totalMoney==============",this.totalPrice);
                    }
                    console.log("======",this.result);
                }else{
                    this.result = []
                    this.totalPrice = 0
                }
            },
            deleteCartGoods(Id){
                console.log("============+++++========",Id);
                axios({
                    url: 'http://localhost:3000/goods/deleteCartGoods',
                    method: 'delete',
                    data:{
                        Id,
                    }
                }).then(res =>{
                    location.reload()
                    // console.log("------------=========",res);
                }).catch((error) => {
                    console.log(error)
                })

            },
            onLoad(){//上拉加载函数
                setTimeout(()=>{
                    this.getcartInfo()
                },1000)
            },
            onRefresh(){//下拉刷新
                setTimeout(() => {
                    this.isRefresh = false;
                    this.goodList=[]
                    this.pageNum = 1
                    this.onLoad()
                }, 500);
            },
            goodsStockQuery(id,quanityObj){
                axios({
                        url: 'http://localhost:3000/goods/goodsStockQuery',
                        method: 'post',
                        data:{
                            goodsId:id,
                        }
                    }).then(res =>{
                        // console.log("-----res.data-----",res.data.data);
                        this.goodsStock = res.data.data
                        let isStock = true
                        console.log("==============goodStock===========",this.goodsStock);
                        for(let item in this.goodsStock){
                            // console.log("-------item-------",this.goodsStock);
                            if(this.goodsStock[item]<quanityObj[item]){
                                Toast.fail(item+'库存数量不足')
                                isStock = false
                                break
                            }
                        }
                        if(isStock){
                            let selectGoods = []
                            for(let item of this.result){
                                for(let val of this.cartInfo){
                                    if(item === val.goodsId){
                                        selectGoods.push(val)
                                    }
                                }
                            }
                            let settleGoods = {goods:selectGoods}
                            localStorage.settleGoods = JSON.stringify(settleGoods)
                            // console.log("selectGoods=======",settleGoods);
                            this.$router.push({ name:'productOrder'})
                        }
                    }).catch((error) => {
                        console.log(error)
                    })
                    // console.log("======goodsQuanity=====",goodsQuanity);
                    console.log("======id=====",id);
            },
            onSubmit(){
                if(this.userId){
                    if(this.result.length>0){
                        let goodsQuanity = []   //商品数量列表
                        let id = []            //商品id列表
                        let quanityObj = {}    //购物车商品数量对象
                        for(let item of this.result){
                            for(let val of this.cartInfo){
                                if(item === val.goodsId){
                                goodsQuanity.push(val.quanity)
                                id.push(val.goodsId)
                                quanityObj[val.name] = val.quanity
                                }
                            }
                        }
                    // console.log("-----quanityObj-----",quanityObj);
                        this.goodsStockQuery(id,quanityObj)
                        
                    }else{
                        Toast.fail('请先选择要结算的商品')
                    }
                }else{
                    Toast.fail('请先登录账号')
                }
            },
            jumpLogin(){
                this.$router.push({ path:'/login' })
            },
            changeQuanity(id,quanity){
                console.log("-----id---quanity----",id,quanity);
                axios({
                    url: 'http://localhost:3000/goods/changCartGoodsQuanity',
                    method: 'post',
                    data:{
                        Id: id,
                        quanity,
                    }
                }).then(res =>{
                    // location.reload()
                    console.log("------------=========",res);
                }).catch((error) => {
                    console.log(error)
                })
            }
        },
    }
</script>

<style lang="scss" scoped>
    @import '../assets/css/notice.css';
    #cartInfo{
    overflow: scroll;
}
.cart-list{
    /* // background-color: #fff; */
    background-color: #FDF5E6;
}
.goods{
    display: flex;
    flex-direction: row; /* //横向布局 */
    flex-wrap: nowrap;   /*不换行*/
    padding: 0.5rem;
    font-size: .8rem;
    /* width: 100%; */
    border-bottom: 1px solid #e4e7ed;
}
.goods-img{
    flex: 9;
}
.goods-text{
    flex: 15;
    padding-left:10px;
    margin-top: 2rem;
}
.goods-text-bottom{
    display: flex;
    padding-top: 10px;
    
}
.goods-text-bottom .goods-price{
    margin: 10px 20px auto 2rem;
    /* // margin-left: 2.3rem;
    // margin-right: 24px; */
}
.goods-text-bottom .goods-count{
    background-color: white;
    margin-top: 6px;
}
.cart-list .van-checkbox-group .van-checkbox__icon .van-icon {
    margin-left: 50px;
}
.van-submit-bar .van-submit-bar__bar{
     position: relative;
     bottom: 56px;
}
.cart-deleteBtn{
    float: right;
    color: blue;
    font-size: 13px;
    margin-top: 8px;
    margin-right: 8px;
}
</style>